<template>
  <div class="checkout-page">
    <div class="page-header">
      <div class="header-content">
        <el-button @click="$router.push('/cart')">返回购物车</el-button>
        <h1>确认订单</h1>
      </div>
    </div>

    <div class="checkout-content" v-loading="loading">
      <el-card class="order-section">
        <template #header>
          <div class="section-header">
            <h2>收货信息</h2>
          </div>
        </template>
        
        <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="100px">
          <el-form-item label="收货人" prop="name">
            <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="收货地址" prop="address">
            <el-input v-model="addressForm.address" type="textarea" placeholder="请输入详细地址" />
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="order-section">
        <template #header>
          <div class="section-header">
            <h2>订单商品</h2>
          </div>
        </template>

        <div class="order-items">
          <div v-for="item in orderItems" :key="item.id" class="order-item">
            <div class="item-image">
              <img :src="item.image" :alt="item.name" />
            </div>
            <div class="item-info">
              <h3>{{ item.name }}</h3>
              <p class="price">¥{{ item.price.toFixed(2) }} × {{ item.quantity }}</p>
            </div>
            <div class="item-subtotal">
              ¥{{ (item.price * item.quantity).toFixed(2) }}
            </div>
          </div>
        </div>
      </el-card>

      <el-card class="order-section">
        <template #header>
          <div class="section-header">
            <h2>支付方式</h2>
          </div>
        </template>

        <el-radio-group v-model="paymentMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
        </el-radio-group>
      </el-card>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总额：</span>
          <span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>运费：</span>
          <span class="amount">¥{{ shipping.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>实付金额：</span>
          <span class="amount">¥{{ (totalAmount + shipping).toFixed(2) }}</span>
        </div>
      </div>

      <div class="checkout-actions">
        <el-button type="primary" size="large" @click="submitOrder" :loading="submitting" v-if="!orderId">
          提交订单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'Checkout',
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const submitting = ref(false)
    const addressFormRef = ref(null)
    const shipping = ref(10) // 固定运费
    const paymentMethod = ref('alipay')
    const orderId = ref(null)

    // 从Vuex获取购物车数据
    const orderItems = computed(() => store.state.cart)
    const user = computed(() => store.state.user || {})
    const addressForm = ref({
      name: '',
      phone: '',
      address: ''
    })

    const addressRules = {
      name: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入收货地址', trigger: 'blur' }
      ]
    }

    const totalAmount = computed(() => store.getters.cartTotal)

    // 自动填充用户信息里的收货地址
    onMounted(async () => {
      if (user.value) {
        // 如果信息不全，自动拉取
        if (!user.value.name || !user.value.phone || !user.value.address) {
          try {
            const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
            addressForm.value.name = res.data.name || ''
            addressForm.value.phone = res.data.phone || ''
            addressForm.value.address = res.data.address || ''
            // 同步更新store.state.user
            store.commit('SET_USER', res.data)
          } catch (e) {
            addressForm.value.name = ''
            addressForm.value.phone = ''
            addressForm.value.address = ''
          }
        } else {
          addressForm.value.name = user.value.name || ''
          addressForm.value.phone = user.value.phone || ''
          addressForm.value.address = user.value.address || ''
        }
      }
    })

    // 提交订单，状态为pending
    const submitOrder = async () => {
      if (!addressFormRef.value) return
      try {
        await addressFormRef.value.validate()
        submitting.value = true
        // 创建订单数据
        const orderData = {
          shipping: shipping.value,
          paymentMethod: paymentMethod.value,
          shippingAddress: {
            name: addressForm.value.name,
            phone: addressForm.value.phone,
            address: addressForm.value.address
          },
          status: 'pending',
          createTime: new Date().toISOString(),
          userId: user.value.id
        }
        // 使用store action创建订单
        const order = await store.dispatch('createOrder', orderData)
        if (order) {
          ElMessage.success('订单已提交，请前往支付')
          orderId.value = order.id
          // 跳转到支付页面
          router.push({ path: `/pay/${order.id}` })
        }
      } catch (error) {
        if (error.name === 'ValidationError') {
          ElMessage.warning('请填写完整的收货信息')
        } else {
          console.error('Error submitting order:', error)
          ElMessage.error('订单提交失败，请重试')
        }
      } finally {
        submitting.value = false
      }
    }

    return {
      loading,
      submitting,
      addressForm,
      addressFormRef,
      addressRules,
      orderItems,
      totalAmount,
      shipping,
      paymentMethod,
      submitOrder,
      orderId
    }
  }
}
</script>

<style scoped>
.checkout-page {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
}

.order-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #2c3e50;
}

.item-info .price {
  margin: 0;
  color: #606266;
}

.item-subtotal {
  font-size: 16px;
  color: #f56c6c;
  font-weight: 500;
}

.order-summary {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
  margin-top: 30px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  color: #606266;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #dcdfe6;
  color: #303133;
  font-weight: 500;
}

.summary-item .amount {
  color: #f56c6c;
  font-weight: 500;
}

.checkout-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-radio-group {
  display: flex;
  gap: 30px;
}
</style> 